//
//  WPSearchTableVC.m
//  wobingwoyi
//
//  Created by WGP on 16/7/25.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPSearchVC.h"
#import "WPDetailSearchView.h"
#import "WPSearchDataManager.h"
#import "WPSearchHistoryCell.h"
#import "WPResultTableView.h"
#import "WPMRModel.h"
#import "WPMineLoginVC.h"
#import "WPSearchCasesReadingVC.h"
#import "WPCoinTopUp.h"

#define fontCOLOR  RGB_COLOR(163, 163, 163)

@interface WPSearchVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UIView *noCaseView;
@property(nonatomic,strong) WPDetailSearchView *searchView;
@property(nonatomic,strong)UITableView *historyTableView;
@property(nonatomic,strong)WPResultTableView *resultTableView;
@property(nonatomic,strong)NSArray *hisArr;
@property(nonatomic,copy)NSString *lastWord;
@property(nonatomic,strong)NSMutableArray *models;

@property(nonatomic,strong)UIAlertView *alertView;
@property(nonatomic,strong)UIView *windowView;
@property(nonatomic,strong)UIButton *coverBtn;
@property(nonatomic,assign)int userGlod;
@property(nonatomic,assign)int recordgold;
@property(nonatomic,strong)WPMRModel *selectedModel;
@property(nonatomic,strong)NSIndexPath *selectedIndex;
@property(nonatomic,assign)int indexPage;

@end

static NSString *ID = @"WPSearchHistoryCell";

@implementation WPSearchVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    1.隐藏系统的返回按钮
    [self.navigationItem setHidesBackButton:YES];
    
    self.navigationController.navigationBar.hidden = NO;
   
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (self.isFiveDiseases)
    {
        self.navigationController.navigationBar.hidden = YES;
    }
}

-(UIView *)noCaseView
{
    if (_noCaseView == nil)
    {
        _noCaseView = [[UIView alloc] init];
        _noCaseView.backgroundColor = GlobalBgColor;
        [self.view addSubview:_noCaseView];
        
        [_noCaseView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 44)];
        headView.backgroundColor = [UIColor whiteColor];
//        [_noCaseView addSubview:headView];
        
        UILabel *label = [UILabel new];
        label.text = @"相关病例";
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = RGB_SAME(102);
        [headView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headView).offset(15);
            make.centerY.equalTo(headView);
        }];
        
        UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"collection_record"]];
        [iconView sizeToFit];
        [_noCaseView addSubview:iconView];
        
        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_noCaseView).offset(150);
            make.centerX.equalTo(_noCaseView);
        }];
        
        UILabel *tipLabel = [UILabel new];
        tipLabel.numberOfLines = 0;
        tipLabel.textAlignment = NSTextAlignmentCenter;
        tipLabel.font = [UIFont systemFontOfSize:14];
        tipLabel.textColor = GloballightFontColor;
        NSString *string = @"没有搜索到您需要的病例哦\n       试试别的关键字吧";
        
        NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
        paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
        
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:paraStyle};
        
        NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:string attributes:dic];
        tipLabel.attributedText = attributeStr;
        [_noCaseView addSubview:tipLabel];
        
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noCaseView);
            make.top.equalTo(iconView.mas_bottom).offset(30);
        }];
    }
    return _noCaseView;
}

-(UITableView *)historyTableView
{
    if (_historyTableView == nil)
    {
        _historyTableView = [UITableView new];
        _historyTableView.delegate = self;
        _historyTableView.dataSource = self;
        _historyTableView.bounces = NO;
        _historyTableView.backgroundColor = GlobalBgColor;
        _historyTableView.tableFooterView = [UIView new];
        _historyTableView.tableFooterView.backgroundColor = GlobalBgColor;
        _historyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_historyTableView registerClass:[WPSearchHistoryCell class] forCellReuseIdentifier:ID];
        [_historyTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        
        [self.view addSubview:_historyTableView];
        
        [_historyTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _historyTableView;
}

-(WPResultTableView *)resultTableView
{
    if (_resultTableView == nil)
    {
        _resultTableView = [WPResultTableView new];
        _resultTableView.bounces = NO;
        
        //    上拉刷新控件
        MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [self loadMoreData];
            
        }];
        _resultTableView.mj_footer = mj_footer;
        mj_footer.automaticallyRefresh = NO;
        mj_footer.automaticallyHidden = NO;
        [self.view addSubview:_resultTableView];
        
        __weak typeof(self) weakSelf = self;
        _resultTableView.didSelectedBlock = ^(NSIndexPath *indexPath)
        {
            weakSelf.selectedIndex = indexPath;
            
                WPMRModel *model = weakSelf.models[indexPath.item-1];
                weakSelf.selectedModel = model;
                
                if (model.payable)
                {
                    if ([WPUserAccountViewModel sharedInstance].userLogin)
                    {
                        NSString *url = @"record/getGoldNum.do";
                        NSDictionary *dict = @{@"recordId":@(model.id)};
                        
                        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                            
                        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            
                            if ([responseObject[@"result"] isEqualToString:@"success"])
                            {
                                //                            是否已经购买过了
                                if ([responseObject[@"detail"][@"status"] intValue])
                                {
                                    
                                    NSString *url = @"record/readRecord.do";
                                    NSDictionary *dict = @{@"recordId":@(model.id)};
                                    
                                    //                                阅读量
                                    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                                        
                                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                        
                                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                        
                                    }];
                                    
                                    
                                    //                                查看病例
                                    WPSearchCasesReadingVC *rirVC = [WPSearchCasesReadingVC new];
                                    rirVC.model = model;
                                    [weakSelf  presentViewController:rirVC animated:YES completion:nil];
                                }
                                else
                                {
                                    weakSelf.recordgold = [responseObject[@"detail"][@"recordGold"] intValue];
                                    weakSelf.userGlod = [responseObject[@"detail"][@"userGold"] intValue];
                                    
                                    [weakSelf showGoldInfomation];
                                }
                            }
                            else
                            {
                                //考虑到账号过期的情况
                                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                                {
                                    //                账号过期
                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:weakSelf cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                                    [alertView show];
                                }
                                else
                                {
                                    [weakSelf showErrorInfoWithStatus:@"网络错误"];
                                }
                            }
                            
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            [weakSelf showErrorInfoWithStatus:@"网络错误"];
                        }];
                    }
                    else
                    {
        
                        [[WPUserAccountViewModel sharedInstance] loginTipWith:^{
        
                            WPMineLoginVC *vc = [WPMineLoginVC new];
                            [weakSelf presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                        }];
                    }
                }
                else
                {
                    //免费病例直接查看
//                    WPSearchCasesReadingVC *rirVC = [WPSearchCasesReadingVC new];
//                    rirVC.model = model;
//                    if (weakSelf.isFiveDiseases)
//                    {
//                        rirVC.isBlack = YES;
//                    }
//                    [weakSelf  presentViewController:rirVC animated:YES completion:nil];
                    
                    WPReadingInvidialRanking *rirVC = [WPReadingInvidialRanking new];
                    rirVC.model = model;
                    rirVC.isDismiss = YES;
                    if (weakSelf.isFiveDiseases)
                    {
                        rirVC.isBlack = YES;
                    }
                    
                    ZNBPanNavigationController *znb = [[ZNBPanNavigationController alloc] initWithRootViewController:rirVC];
                    znb.navigationBar.hidden = YES;
                    [weakSelf.navigationController presentViewController:znb animated:YES completion:nil];
                }
        };
        
        [_resultTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _resultTableView;
}

//未购病例展示弹窗
-(void)showGoldInfomation
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.coverBtn = coverBtn;
    coverBtn.frame = [UIScreen mainScreen].bounds;
    coverBtn.backgroundColor = RGBA_COLOR(51, 51, 51, 0.5);
    [coverBtn addTarget:self action:@selector(coverBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [window addSubview:coverBtn];
    
    UIView *windowView = [UIView new];
    self.windowView = windowView;
    windowView.layer.cornerRadius = 6;
    windowView.layer.masksToBounds = YES;
    windowView.backgroundColor = [UIColor whiteColor];
    [window addSubview:windowView];
    
    [windowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(window).offset(47);
        make.right.equalTo(window).offset(-47);
        make.height.mas_equalTo(295);
        make.top.equalTo(window).offset(186*K_SCALE_FULL);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = GLobalFontColor;
    titleLabel.text = @"确认购买";
    [titleLabel sizeToFit];
    [windowView addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(windowView).offset(26);
        make.centerX.equalTo(windowView);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"chaBtn"] forState:UIControlStateNormal];
    [windowView addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(coverBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [cancelBtn sizeToFit];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(windowView).offset(8);
        make.right.equalTo(windowView).offset(-8);
    }];
    
    UILabel *goodsLabel = [UILabel new];
    goodsLabel.font = [UIFont systemFontOfSize:14];
    goodsLabel.textColor = GLobalFontColor;
    goodsLabel.text = @"购买物件：电子病历";
    [goodsLabel sizeToFit];
    [windowView addSubview:goodsLabel];
    
    [goodsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(windowView).offset(35);
        make.top.equalTo(titleLabel.mas_bottom).offset(26);
    }];
    
    NSString *purchasePriceStr = [NSString stringWithFormat:@"购买价格：%zd医票",self.recordgold];
    NSMutableAttributedString *purchasePrice = [[NSMutableAttributedString alloc] initWithString:purchasePriceStr];
    [purchasePrice addAttributes:@{NSForegroundColorAttributeName:GlobalColor} range:[purchasePriceStr rangeOfString:[NSString stringWithFormat:@"%zd医票",self.recordgold]]];
    
    UILabel *purchasePriceLabel = [UILabel new];
    purchasePriceLabel.font = [UIFont systemFontOfSize:14];
    purchasePriceLabel.textColor = GLobalFontColor;
    purchasePriceLabel.attributedText = purchasePrice;
    [purchasePriceLabel sizeToFit];
    [windowView addSubview:purchasePriceLabel];
    
    [purchasePriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(goodsLabel);
        make.top.equalTo(goodsLabel.mas_bottom).offset(20);
    }];
    
    
    NSString *currentGoldStr = [NSString stringWithFormat:@"当前医票：%zd医票",self.userGlod];
    NSMutableAttributedString *currentGoldAtt = [[NSMutableAttributedString alloc] initWithString:currentGoldStr];
    [currentGoldAtt addAttributes:@{NSForegroundColorAttributeName:GlobalColor} range:[currentGoldStr rangeOfString:[NSString stringWithFormat:@"%zd医票",self.userGlod]]];
    
    UILabel *currentGlodLabel = [UILabel new];
    currentGlodLabel.font = [UIFont systemFontOfSize:14];
    currentGlodLabel.textColor = GLobalFontColor;
    currentGlodLabel.attributedText = currentGoldAtt;
    [currentGlodLabel sizeToFit];
    [windowView addSubview:currentGlodLabel];
    
    [currentGlodLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(purchasePriceLabel);
        make.top.equalTo(purchasePriceLabel.mas_bottom).offset(20);
    }];
    
    NSString *title = (self.recordgold > self.userGlod) ? @"医票不足，请充值" : @"确认购买";
    UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [okBtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
    [okBtn setBackgroundImage:[UIImage imageNamed:@"highLight"] forState:UIControlStateHighlighted];
    [okBtn addTarget:self action:@selector(okBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [okBtn setTitle:title forState:UIControlStateNormal];
    okBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [windowView addSubview:okBtn];
    
    [okBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(windowView).offset(19);
        make.right.equalTo(windowView).offset(-19);
        make.top.equalTo(currentGlodLabel.mas_bottom).offset(26);
        make.height.mas_equalTo(40);
    }];
    
    UILabel *tipLabel = [UILabel new];
    tipLabel.text = @"病历购买后将置入病历收藏里";
    tipLabel.textColor = GloballightFontColor;
    tipLabel.font = [UIFont systemFontOfSize:13];
    [tipLabel sizeToFit];
    [windowView addSubview:tipLabel];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(windowView);
        make.top.equalTo(okBtn.mas_bottom).offset(15);
    }];
}

-(void)okBtnDidClick
{
    if (self.recordgold <= self.userGlod)
    {
        //        通知阅读量
        NSString *url = @"record/readRecord.do";
        NSDictionary *dict = @{@"recordId":@(self.selectedModel.id)};
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if([responseObject[@"result"] isEqualToString:@"success"])
            {
                [self coverBtnDidClick];
                
                [self showSuccessInfoWithStatus:@"付费成功"];
                
                //                    免费病例直接查看
                WPSearchCasesReadingVC *rirVC = [WPSearchCasesReadingVC new];
                rirVC.model = self.selectedModel;
                [self  presentViewController:rirVC animated:YES completion:nil];
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    [alertView show];
                }
                else
                {
                    [self showErrorInfoWithStatus:@"付费失败,请稍后重试"];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self showErrorInfoWithStatus:@"网络错误"];
            
        }];
    }
    else
    {
        //        跳转到购买金币界面
        [self coverBtnDidClick];
        
        
        //        调到购买金币界面去购买金币
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WPGoldCoinVC" bundle:nil];
        WPCoinTopUp *gcVC = [sb instantiateViewControllerWithIdentifier:@"goldTopUp"];
        gcVC.isDismiss = YES;
        
        [self presentViewController:gcVC animated:YES completion:nil];
    
        
        //重新比较一下金币数量
        gcVC.backBlock = ^
        {
//            购买金币后
            self.resultTableView.didSelectedBlock(self.selectedIndex);
        };
    }
}


-(void)coverBtnDidClick
{
    [self.windowView removeFromSuperview];
    [self.coverBtn removeFromSuperview];
    
    self.windowView = nil;
    self.coverBtn = nil;
}


-(void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self noCaseView];
    [self resultTableView];
    [self historyTableView];
    
    self.searchView = [[WPDetailSearchView alloc] initWith:^{
        
        [self.navigationController popViewControllerAnimated:NO];
        [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    }];
    self.searchView.textField.delegate = self;
    
    //是否是五大疾病的搜索
    if (self.isFiveDiseases)
    {
        self.searchView.textField.backgroundColor = RGB_SAME(245);
        self.searchView.bgView.backgroundColor = RGB_SAME(245);
        [self.searchView.cancelBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        
        [self.noCaseView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(64);
        }];
        
        [self.historyTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(64);
        }];
        
        [self.resultTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(64);
        }];
    }
    
    [self.searchView.textField addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventEditingChanged];
    self.navigationItem.titleView = self.searchView;
    
    [self.searchView.textField becomeFirstResponder];
}

#pragma mark - 数据源方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        if (self.hisArr.count > 0)
        {
            return self.hisArr.count + 1 + 1;
        }else
        {
            return 0;
        }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        if(indexPath.row ==0){
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
            cell.textLabel.text = @"搜索历史";
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textColor = fontCOLOR;
            return cell;
        }else if (indexPath.row == self.hisArr.count+1){
             WPSearchHistoryCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
            cell.isHideLine = YES;
            cell.textLabel.text = @"清除历史记录";
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textColor = fontCOLOR;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            return cell;
        }else{
             WPSearchHistoryCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
            cell.textLabel.text = self.hisArr[indexPath.row-1];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textColor = GLobalFontColor;
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
            cell.isHideLine = NO;
            return cell;
        }
    }else{
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    }else{
        return 10;
    }
}

#pragma mark - tableView的代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.hisArr.count+1) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"确定清除搜索历史?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        self.alertView = alertView;
        [alertView show];
    }
    else if (indexPath.item == 0)
    {
        
    }
    else
    {
        self.searchView.textField.text = self.hisArr[indexPath.item-1];
        [self textFieldShouldReturn:self.searchView.textField];
    }
}

#pragma mark - textField代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length > 0)
    {
//        if ([self.lastWord isEqualToString:textField.text])
//        {
//            self.resultTableView.models = self.models;
//            return YES;
//        }
        self.lastWord = textField.text;
        
        
        NSString *url = @"record/searchRecord.do";
        NSDictionary *dict = @{@"condition":textField.text};
        
        [self showWithStatus:@"正在加载"];
        
//        清空缓存
        [self.models removeAllObjects];
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self dismiss];
            
            NSDictionary *responseDict = (NSDictionary *)responseObject;
            if ([responseDict[@"result"] isEqualToString:@"success"])
            {
                self.indexPage = 1;
                
                if([responseDict[@"detail"] count])
                {
                    self.resultTableView.hidden = NO;
                    for (NSDictionary *dict in responseDict[@"detail"])
                    {
                        WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                        [self.models addObject:model];
                    }
                    
                    self.resultTableView.searchStr = textField.text;
                    self.resultTableView.models = self.models;
                    
                    //不满一页就隐藏
                    if ([responseDict[@"detail"] count] < 10)
                    {
                        self.resultTableView.mj_footer.hidden = YES;
                    }
                }
                else
                {
                    self.resultTableView.hidden = YES;
                }
                
                [textField resignFirstResponder];
                [WPSearchDataManager saveSearchText:textField.text];
                self.hisArr = [[[WPSearchDataManager readNSUserDefaults] reverseObjectEnumerator] allObjects];
                [self.historyTableView reloadData];
                
                self.historyTableView.hidden = YES;
            }
            else
            {
                [self showErrorInfoWithStatus:@"服务器错误"];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self dismiss];
            [self showErrorInfoWithStatus:@"网络错误"];
        }];
    
    }
    return YES;
}

-(void)loadMoreData
{
    NSString *url = @"record/searchRecord.do";
    NSDictionary *dict = @{@"condition":self.lastWord,@"page":@(self.indexPage)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            self.indexPage++;
            
            if([responseDict[@"detail"] count])
            {
                for (NSDictionary *dict in responseDict[@"detail"])
                {
                    WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                    [self.models addObject:model];
                }
                
                self.resultTableView.searchStr = self.lastWord;
                self.resultTableView.models = self.models;
                
                //不满一页就隐藏
                if ([responseDict[@"detail"] count] < 10)
                {
                    self.resultTableView.mj_footer.hidden = YES;
                }
                
                [self.resultTableView.mj_footer endRefreshing];
            }
            else
            {
                [self.resultTableView.mj_footer endRefreshing];
            }
        }
        else
        {
            [self showErrorInfoWithStatus:@"服务器错误"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)valueChanged:(UITextField *)textField
{
    if(textField.text.length)
    {

    }
    else
    {
        self.historyTableView.hidden = NO;
    }
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchView.textField resignFirstResponder];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (self.alertView == alertView)
    {
        if (buttonIndex == 1) {
            [WPSearchDataManager removeAllArray];
            self.hisArr = nil;
            [self.historyTableView reloadData];
        }
    }
    else
    {
        if (buttonIndex == 0)
        {
            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        }
    }
}

#pragma mark - 懒加载

-(NSArray *)hisArr
{
    if (!_hisArr) {
        
        _hisArr = [WPSearchDataManager readNSUserDefaults];
        _hisArr = [[_hisArr reverseObjectEnumerator] allObjects];
        if (!_hisArr) {
            
            _hisArr = [NSMutableArray array];
        }
    }
    return _hisArr;
}

-(NSMutableArray *)models
{
    if (_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}

@end









